var common = require('../template/getCode.js');
var util = require('../../utils/util.js');
import { $wuxButton } from '../../components/wux'
var app = getApp();
var that;
var optionId; //活动的Id
var publisherId; //活动发布者的Id
var joinpId; //如果当前用户已经加入，该活动在联系表中的Id
var eventMoreId; //当前活动的活动扩展表Id
var commentlist;
var joinlist;
var likerlist;
let commentText; //评论输入框内容
Page({
  data: {
    accounts: ["手机", "微信", "QQ"],
    accountIndex: 0,
    actStatusArray: ["准备中", "进行中", "已结束"],
    statusIndex: 0,
    realname: "",
    contactValue: "",
    showTopTips: false, //是否显示提示
    TopTips: '', //提示的内容
    linkmainHe: false,
    linkjoinHe: false,
    //----------------
    tag_select: 0,
    limit: 5,
    showImage: false,
    loading: false,
    isdisabled: false,
    commentLoading: false,
    isdisabled1: false,
    recommentLoading: false,
    commentList: [],
    joinList: [],
    likerList: [],
    agree: 0,
    favo: 0,
    join: 0,
    isMe: false,
    isToResponse: false,
    autoplay: true,
    interval: 3000,
    duration: 1000,

    status: 0,//tab切换按钮
    adminId: "",
    adminname: "",
    adcontactWay: "",
    adcontactValue: "",
    showCommentDialog: false,//评论输入框显示
    commentInputHolder: "请输入评论内容",//评论输入框提示
    //----------------------------------
    index: 2,
    opened: !1,
    style_img: '',


    //new ------------------------------
    eventStatus: 3,
    eventIsFull: 1,
    userType: 2,
    eventId: null,
    currentSceneIsShare: false
  },

  //生成活动二维码
  showQrcode: function () {
    var path = '/pages/detail/detail?actid=' + optionId + "&pubid=" + publisherId;
    var width = 40;
    var that = this;
    Bmob.generateCode({ "path": path, "width": width }).then(function (obj) {
      console.log(obj);
      that.setData({
        imageBytes: obj.imageBytes,
        codeHehe: true
      })
    }, function (err) {
      common.showTip('生成二维码失败' + err);
    });
  },

  //关闭二维码弹窗
  closeCode: function () {
    this.setData({
      codeHehe: false
    })
  },
  //打开活动群二维码弹窗
  showqrcode: function () {
    this.setData({
      qrcodeHe: true
    })
  },

  //关闭活动群二维码弹窗
  closeqrcode: function () {
    this.setData({
      qrcodeHe: false
    })
  },

  //打开发布者联系方式弹窗
  showmainLink: function () {
    this.setData({
      linkmainHe: true
    })
  },
  //关闭发布者联系方式弹窗
  closemainLink: function () {
    this.setData({
      linkmainHe: false
    })
  },
  //打开加入者联系方式弹窗
  showjoinLink: function (e) {
    var id = e.currentTarget.dataset.id;
    that.setData({
      currJoinId: id
    })
    var joinList2 = that.data.joinList;
    joinList2.forEach(function (item) {
      if (item.id === id) {
        item.linkjoinHe = true;
      }
    })
    this.setData({
      joinList: joinList2
    })
  },
  //关闭加入者联系方式弹窗
  closejoinLink: function () {
    var id = that.data.currJoinId;
    var joinList2 = that.data.joinList;
    joinList2.forEach(function (item) {
      if (item.id === id) {
        item.linkjoinHe = false;
      }
    })
    this.setData({
      joinList: joinList2
    })
  },

  //复制联系方式
  copyLink: function (e) {
    var value = e.target.dataset.value;
    wx.setClipboardData({
      data: value,
      success() {
        common.dataLoading("复制成功", "success");
        console.log('复制成功')
      }
    })
  },

  //切换tab操作
  changePage: function (e) {
    let id = e.target.id;
    this.setData({
      status: id
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var currentScene = wx.getStorageSync('scene');
    console.log("currentScene" + currentScene)
    if (currentScene != 1001 || currentScene != 1005 || currentScene != 1006 || currentScene != 1022) {
      this.setData({
        currentSceneIsShare: true
      })
    }
    var userId = wx.getStorageSync('user_id');
    wx.setStorageSync("saveEventId", options.id);
    wx.request({
      url: app.globalData.hostName + '/microappointment/activity/itemDetail?eventId=' + options.id + '&userId=' + userId,
      success: function (res) {
        console.log("/microappointment/activity/itemDetail?eventId=" + options.id + "&userId=" + userId + ":", res);
        var eventId = res.data.data.id || null;
        var listPic = res.data.data.pictureUrls || "/image/1.jpg";
        var title = res.data.data.title || "活动名加载中...";
        var publisher = res.data.data.user.username || "";
        var address = res.data.data.location || "";
        var longitude = res.data.data.longitude || "";//经度
        var latitude = res.data.data.latitude || "";//纬度
        var endtimeTemp = res.data.data.expireTime;
        var endtime = util.getDateDiff2(endtimeTemp) || "";
        var acttypename = res.data.data.categoryName || "未分类?";
        var peoplenum = res.data.data.limitNumber || "0";
        if (res.data.data.status == 1) {
          var Statusname = "准备中";
        } else if (res.data.data.status == 2) {
          var Statusname = "进行中";
        } else if (res.data.data.status == 3) {
          var Statusname = "已结束";
        }
        var statusname = Statusname;
        var listContent = res.data.data.content || "活动内容加载中...";
        var agreeNum = res.data.data.likeCount || "0";
        var joinnumber = res.data.data.attendedCount || "0";
        var commNum = res.data.data.comments.length || "0";
        var eventStatus = res.data.data.status || 3;
        var eventIsFull = res.data.data.isFull || 0;
        var userType = res.data.data.userType || 0;
        var commentlist = res.data.data.comments || 0;
        var joinList = res.data.data.contracts || null;


        if (res.data.code == 1) {
          that.setData({
            eventId: eventId,
            listPic: listPic,
            listTitle: title,
            publisher: publisher,
            address: address,
            endtime: endtime,
            acttypename: acttypename,
            peoplenum: peoplenum,
            statusname: statusname,
            listContent: listContent,
            agreeNum: agreeNum,
            joinnumber: joinnumber,
            commNum: commNum,
            commentList: commentlist,
            joinList: joinList,
            loading: true,

            eventStatus: eventStatus,
            eventIsFull: eventIsFull,
            userType: userType
          })
        }
      }
    })




    //this.initButton();
    that = this;
    var openid = wx.getStorageSync("user_openid");
    optionId = options.actid;
    publisherId = options.pubid;
    var buttons2 = new Array()
    wx.getStorage({ //判断当前发布人是不是自己
      key: 'user_id',
      success: function (ress) {
        if (publisherId == ress.data) {

          that.setData({
            favo: 3, //表示无法收藏
            join: 3, //已经无法加入
            isMe: true,
          })
          console.log("这是我的发起");
        }
      },
    })

    
  },
  swiperchange: function (e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.hideToast()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },


  //-----------------------------------------------------------
  showCommentDialog: function (e) {//显示我要评论弹窗
    this.setData({
      showCommentDialog: true,
      commentInputHolder: typeof e == 'string' ? e : "请输入评论内容",
    })
  },
  hideCommentDialog: function () {//隐藏我要评论弹窗
    this.setData({
      showCommentDialog: false,
      isToResponse: false
    });
  },

  commentText: function (e) {//评论内容赋值
    commentText = e.detail.value
  },

  //点击评论itam
  commentTap: function (e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    let commentActions;
    if (item.uid == wx.getStorageSync('user_id')) {//自己的评论，可以删除
      commentActions = ["删除"]
    } else {
      commentActions = ["回复"]
    }
    wx.showActionSheet({
      itemList: commentActions,
      success: function (res) {
        let button = commentActions[res.tapIndex];
        if (button == "回复") {
          that.setData({
            pid: item.uid,
            isToResponse: true,
            responseName: item.username
          })

          that.showCommentDialog("回复" + item.username + "：");
        } else if (button == "删除") {
          //删除评论
          var Comments = Bmob.Object.extend("Comments");
          var comment = new Bmob.Query(Comments);
          comment.get(item.id, {
            success: function (result) {
              result.destroy({
                success: function (res) {
                  common.dataLoading("删除成功", "success");
                  console.log("删除成功");

                },
                error: function (res) {
                  console.log("删除评论错误");
                }
              })
            }
          })
          //活动表中评论数量-1
          var Events = Bmob.Object.extend("Events");
          var queryEvents = new Bmob.Query(Events);
          queryEvents.get(optionId, {
            success: function (object) {
              object.set("commentnum", object.get("commentnum") - 1);
              object.save();
            }
          })
          that.onShow();
        }
      }
    });
  },

  //评论活动
  publishComment: function (e) {
    let that = this;
    var isReply = false;
    if (!commentText || commentText.length == 0) {
      this.setData({
        showTopTips: true,
        TopTips: '请输入评论内容'
      });
      setTimeout(function () {
        that.setData({
          showTopTips: false
        });
      }, 3000);
    } else {
      that.setData({
        isdisabled: true,
        commentLoading: true
      })
      var userId = wx.getStorageSync('user_id');
      var eventId = that.data.eventId;
      wx.request({
        url: app.globalData.hostName + '/microappointment/comment',
        method: 'POST',
        data: {
          "content": commentText, 	//评论内容
          "eventId": eventId,		// 活动id
          "publisherId": userId	// 发布者id
        },
        success: function (res) {
          var tempcommentlist = new Array()
          tempcommentlist = that.data.commentList;
          var nickName = wx.getStorageSync('user_nickName');
          var commentData = {
            "content": commentText,
            "publisherName": nickName
          };
          tempcommentlist.push(commentData);
          that.setData({
            commentList: tempcommentlist
            
          })
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000
          })
        },
        error: function (res, error) {

        }
      })
      that.hideCommentDialog();
    }
    setTimeout(function () {
      that.setData({
        showTopTips: false
      });
    }, 1000);
  },

  bindKeyInput: function (e) {
    this.setData({
      publishContent: e.detail.value
    })
  },
  //查看发起大图
  seeActBig: function (e) {
    wx.previewImage({
      current: that.data.listPic, // 当前显示图片的http链接
      urls: [that.data.listPic] // 需要预览的图片http链接列表
    })
  },
  //查看发起大图
  seeqrCodeBig: function (e) {
    wx.previewImage({
      current: that.data.qrcode, // 当前显示图片的http链接
      urls: [that.data.qrcode] // 需要预览的图片http链接列表
    })
  },

  //查看活动地图位置
  viewActAddress: function () {
    let latitude = this.data.latitude;
    let longitude = this.data.longitude;
    wx.openLocation({ latitude: latitude, longitude: longitude })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log(this.data.listTitle);
    var saveEventId = wx.getStorageSync('saveEventId');
    return {
      title: this.data.listTitle,
      path: "/pages/detail/detail?id=" + saveEventId,
      imageUrl: this.data.istPic,
      success: function (res) {
        // 转发成功
        wx.showToast({
          title: '转发成功',
          icon: 'success'
        });
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '转发失败',
          icon: 'fail'
        });
      }
    }
  },

  //-----------------加入代码------------
  //现在加入功能
  clickJoin: function (event) {
    var eventIsFull = that.data.eventIsFull;
    var userType = that.data.userType;
    if (eventIsFull == 1) {  //如果人加入满了
      wx.showModal({
        title: '温馨提示',
        content: '此活动参加人数已满',
        showCancel: true,
      })
      
    } else if (userType == 1) {//如果已经加入，则不弹出表单，点击取消加入（删除有关消息）
      wx, wx.showModal({
        title: '温馨提示',
        content: '确定取消加入吗？',
        showCancel: true,
        success: function (res) {
          if (res.confirm) {//如果点击确认
            that.setData({
              status: 0
            });
            var eventId = that.data.eventId;
            var userId = wx.getStorageSync('user_id');
            wx.request({
              url: app.globalData.hostName + '/microappointment/activity/unjoin?eventId=' + eventId + '&userId=' + userId,
              method: 'GET',
              success: function (res) {
                wx.showToast({
                  title: '取消加入成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.navigateBack({
                  delta: 1
                })
              },
              error: function (res, error) {

              }
            })

          }
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else if (userType == 2) {
      this.setData({
        showDialog: !this.data.showDialog
      });
    }
  },

  //关闭弹出联系表单
  closeJoin: function () {
    this.setData({
      showDialog: !this.data.showDialog
    });
  },

  //关闭修改联系信息弹窗
  closeUpdJoin: function () {
    this.setData({
      showUpdDialog: false
    });
  },

  //关闭弹出改变状态表单
  closeChange: function () {
    this.setData({
      showStuDialog: false
    });
  },

  //改变发起状态index
  changeStatus: function (e) {
    this.setData({
      statusIndex: e.detail.value
    })
  },

  //改变联系方式
  bindAccountChange: function (e) {
    this.setData({
      accountIndex: e.detail.value
    })
  },
  //改变修改信息时的联系方式
  updjoinChange: function (e) {
    this.setData({
      jocountIndex: e.detail.value
    })
  },

  //改变活动状态操作
  stuSubmit: function (event) {
    var statusIndex = that.data.statusIndex;

    var status = parseInt(statusIndex) + 1;
    var eventId = that.data.eventId;
    wx.request({
      url: app.globalData.hostName + '/microappointment/activity/updateStatus?status=' + status + '&eventId=' + eventId,
      method: 'GET',
      success: function (res) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 1
        })
      },
      error: function (res, error) {

      }
    })

    that.onShow();
  },

  //加入操作
  joinSubmit: function (event) {
    var join = that.data.join;
    var contactindex = that.data.accountIndex;
    if (join == "0") { // 未加入，点击加入
      that.setData({
        join: 1
      })
    }
    else if (join == "1") { //已加入，点击取消加入
      that.setData({
        join: 0
      })
    }
    if (contactindex == 0) {
      var contactWay = "手机号";
    } else if (contactindex == 1) {
      var contactWay = "微信号";
    } else if (contactindex == 2) {
      var contactWay = "QQ号";
    }
    var realname = event.detail.value.realname;
    var contactValue = event.detail.value.contactValue;
    var wxReg = new RegExp("^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$");
    var qqReg = new RegExp("[1-9][0-9]{4,}");
    var phReg = new RegExp("0?(13|14|15|17|18|19)[0-9]{9}");
    var nameReg = new RegExp("^[\u4e00-\u9fa5]{2,4}$");
    if (realname == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入姓名/网名'
      });
    }/* else if (realname != "" && !nameReg.test(realname)) {
      this.setData({
        showTopTips: true,
        TopTips: '真实姓名一般为2-4位汉字'
      });
    }else if (contactValue == "" || true) {
      this.setData({
        showTopTips: true,
        TopTips: '请输入联系方式'
      });
    } else if (contactWay == "微信号" && !wxReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: '微信号格式不正确'
      });
    } else if (contactWay == "手机号" && !phReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: '手机号格式不正确'
      });
    } else if (contactWay == "QQ号" && !qqReg.test(contactValue)) {
      this.setData({
        showTopTips: true,
        TopTips: 'QQ号格式不正确'
      });
    } */ else {
      var eventId = that.data.eventId;
      var userId = wx.getStorageSync('user_id');
      var contactIndexNumber = parseInt(contactindex) +1;
      wx.request({
        url: app.globalData.hostName + '/microappointment/activity/join',
        method: 'POST',
        data:
        {
          "eventId": eventId,
          "attendUserId": userId,
          "contractType": contactIndexNumber, // 1为手机号 2为微信号 3 为qq号
          "contractNum": contactValue,
          "attendUsername": realname
        },
        success: function (res) {
          wx.showModal({
            title: '提示',
            content: '加入成功',
            showCancel: 'false',
            success: function (res) {
              wx.switchTab({
                url: '/pages/center/center'
              })
            }
          })
        },
        error: function (res, error) {

        }
      })
    }
    setTimeout(function () {
      that.setData({
        showTopTips: false
      });
    }, 1000);
  },

  editEvent: function () {
    var eventId = that.data.eventId;
    wx.navigateTo({
      url: "/pages/detail/update-event/update-event?id=" + eventId
    })
  },

  updateEventStatus: function () {
    this.setData({
      showStuDialog: true
    });
  },

  switchChange(e) {
    e.detail.value ? this.button.open() : this.button.close()
  },
  pickerChange(e) {
    const index = e.detail.value
    const position = this.data.types[index]
    this.initButton(position)
  },

  goToIndex: function() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }

})
//根据联系方式确定序号
function getContactIndex(name) {
  var accountIndex = 0;
  if (name == "微信号") accountIndex = 0;
  else if (name == "QQ号") accountIndex = 1;
  else if (name == "手机号") accountIndex = 2;
  return accountIndex;
}

//根据活动类型获取活动类型名称
function getTypeName(acttype) {
  var acttypeName = "";
  if (acttype == 1) acttypeName = "运动";
  else if (acttype == 2) acttypeName = "游戏";
  else if (acttype == 3) acttypeName = "交友";
  else if (acttype == 4) acttypeName = "旅行";
  else if (acttype == 5) acttypeName = "读书";
  else if (acttype == 6) acttypeName = "竞赛";
  else if (acttype == 7) acttypeName = "电影";
  else if (acttype == 8) acttypeName = "音乐";
  else if (acttype == 9) acttypeName = "其他";
  return acttypeName;
}
